package com.ysl.netty.client;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.ysl.netty.domain.SentBody;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.time.LocalDateTime;
import java.util.Scanner;

public class MyClientHandler extends SimpleChannelInboundHandler<String> {


    /**通道活跃时调用*/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //ctx.writeAndFlush("来自于客户端的问候");
        //发送登录信息
        login(ctx.channel());
    }

	@Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //打印远程地址
        System.out.println(ctx.channel().remoteAddress());

        System.out.println("client output：" + msg);
        //ctx.writeAndFlush("客户端from client：" + LocalDateTime.now());
    }

    /**发生异常时调用*/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    public void login(Channel channel)
    {
        Scanner scanner=new Scanner(System.in);
        System.out.println(">>用户ID：");
        String userid=scanner.next();

        SentBody sentBody=new SentBody();
        sentBody.setKey(userid);
        sentBody.setType("login");
        sentBody.setTimestamp(DateUtil.currentSeconds());
        String msg=JSONObject.toJSONString(sentBody);
        /*JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","login");
        jsonObject.put("key",userid);
        String msg=JSONObject.toJSONString(jsonObject);*/
        channel.writeAndFlush(msg);
    }

    //发送消息方法
    private void sendMsg(final Channel channel){
        final Scanner scanner=new Scanner(System.in);
        final String msg="";
        new Thread(new Runnable() {
            public void run() {
                while (true){
                    System.out.println(">>接收人ID：");
                    Integer touserid=scanner.nextInt();
                    System.out.println(">>聊天内容：");
                    String msg=scanner.next();

                    channel.writeAndFlush(msg);
                }
            }
        }).start();
    }
}
